import axios from 'axios'
import Qs from 'qs'
import { Toast } from 'vant';

// 允许携带cookie
axios.defaults.withCredentials=true
// create an axios instance
const service = axios.create({
  baseURL: '', // url = base url + request url
  transformRequest: [data=> {
    // 对 data 进行任意转换处理
    return Qs.stringify(data);
  }],
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['X-Token'] = getToken()
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (Number(res.status) !== 0) {
      //失败提示
      Toast.fail(res.msg);

      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Toast.fail(error.message);
    return Promise.reject(error)
  }
)

export default service
